package elephant.rpc.server.core;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import elephant.rpc.server.service.RPCServiceManager;

/**
 * 本地接口
 * @author skydu
 *
 */
public class LocalProxyFactory{
	//
	private static Logger logger=LoggerFactory.getLogger(LocalProxyFactory.class);
	//
	private LocalInvocationHandler handler;
	private Map<String,Object> serviceProxyMap;
	//
	public LocalProxyFactory(RPCServiceManager serviceManager){
		handler=new LocalInvocationHandler(serviceManager);
		serviceProxyMap=new HashMap<>();
	}
	//
	@SuppressWarnings("unchecked")
	public <T> T getLocalService(Class<T> interfaceClass) {
		if(!interfaceClass.isInterface()){
			throw new IllegalArgumentException("createLocal failed "+interfaceClass+" isnotInterface");
		}
		String name=interfaceClass.getSimpleName();
		Object proxy=serviceProxyMap.get(name);
		if(proxy==null){
			try {
				proxy=Proxy.newProxyInstance(
						interfaceClass.getClassLoader(),
						new Class[]{interfaceClass},
						handler);
				serviceProxyMap.put(name,proxy);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
		return (T)proxy;
	}
}
